package verifyCode

import (
	"RocFamilySystem/pkg/constant"
	"RocFamilySystem/tools/container"
	"context"
	"github.com/go-redis/redis/v8"
	"github.com/mojocn/base64Captcha"
	"log"
	"time"
)

var driverString = base64Captcha.NewDriverString(31, 120, 50, 0, 4, "1234567890QWERTYUIOPASDFGHJKLZXCVBNM", nil, nil, nil)
var redisStore = &RedisStore{}
var captcha = base64Captcha.NewCaptcha(driverString.ConvertFonts(), redisStore)

type RedisStore struct {
	base64Captcha.Store
}

// Set sets the digits for the captcha id.
func (store *RedisStore) Set(id string, value string) error {
	client := container.GetBeanFromContainer("redis.Client").(*redis.Client)
	timeout, _ := context.WithTimeout(context.Background(), time.Second*3)
	return client.Set(timeout, constant.REDIS_KEY_SYS_CAPTCHA+id, value, time.Second*30).Err()
}

// Get returns stored digits for the captcha id. Clear indicates
// whether the captcha must be deleted from the store.
func (store *RedisStore) Get(id string, clear bool) string {
	client := container.GetBeanFromContainer("redis.Client").(*redis.Client)
	timeout, _ := context.WithTimeout(context.Background(), time.Second*3)
	val := client.Get(timeout, constant.REDIS_KEY_SYS_CAPTCHA+id).Val()
	if clear {
		timeout, _ = context.WithTimeout(context.Background(), time.Second*3)
		client.Del(timeout, id)
	}
	return val
}

func (store *RedisStore) Verify(id, answer string, clear bool) bool {
	val := store.Get(id, clear)
	if val == "" {
		return false
	}
	if val == answer {
		return true
	}
	return false
}

// GeneratorVerifyCodeImage 生成验证码图片
func GeneratorVerifyCodeImage() (id, base64Image string) {
	id, base64, value, err := captcha.Generate()
	log.Printf("验证码ID：%s 验证码：%s\n", id, value)
	if err != nil {
		log.Panicln("生成验证码失败！" + err.Error())
	}
	return id, base64
}

// VerifyVerifyCode 验证验证码
func VerifyVerifyCode(id, answer string) bool {
	return captcha.Verify(id, answer, true)
}
